(function (window, $, undefined) {
  'use strict';

  var userData = {};

  main(function () {

    var $formPersonal = $('#form-personal');

    $.validator.addMethod('isUserString', function (value, element) {
      var isValid = /^[a-zA-Z0-9_@#$%^&*!~]+$/.test(value);
      return this.optional(element) || isValid;
    }, '请填写正确值，仅支持字母、数字和部分特殊字符');

    var $validatePersonal = $formPersonal.validate({
      rules: {
        phone: { required: true },
        gender: { required: true },
        password: { isPassword: true, maxlength: 20 },
        vpwd: { isPassword: true, maxlength: 20 }
      },
      messages: {
        phone: { required: '请输入联系电话' },
        gender: { required: '请选择性别' },
        password: { maxlength: '密码最大长度 20' },
        vpwd: { maxlength: '密码最大长度 20' }
      }
    });

    // if (oUser.account === 'admin') {
    //   $formPersonal.find('[type="password"]').attr('disabled', 'disabled');
    // }

    util.get(ajaxURL.SYSTEM + '/sys/user/getSysUserPageList', {
      pageNum: 1,
      pageSize: 15,
      userId: oUser.userId
    }, function (res) {
      userData = res.data[0];
      $formPersonal.find('[data-value="name"]').text(userData.name);
      $formPersonal.find('[data-value="role"]').text(function () {
        var ret = [];
        if (oUser.account === 'admin') {
          return '超级管理员';
        } else {
          $.each(userData.roleList, function (_, item) {
            ret.push(item.name);
          });
        }
        return ret.join('、');
      });
      util.fillForm($formPersonal, {
        phone: userData.phone,
        gender: userData.gender
      });
    });

    $('#btn-save').click(function () {
      if ($validatePersonal.form()) {
        var data = util.formData($formPersonal);
        if (data.password !== data.vpwd) {
          return util.tip.warn('密码与确认密码不一致');
        }
        var saveData = {
          userId: oUser.userId,
          gender: data.gender,
          phone: data.phone
        };
        if (data.password) {
          saveData.password = util.sha666(data.password);
        }

        layer.confirm('确认修改个人信息？', function () {
          util.post(ajaxURL.SYSTEM + '/sys/user/updateUserByUserId?' + $.param(saveData), function (res) {
            util.tip.success('修改成功');
            $formPersonal.find('[type="password"]').val('');
          });
        });

      }
    });


  });
})(window, jQuery);
